package com.jgzx.redis.lock;

import com.jgzx.redis.config.CacheKeyEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * @author jackesy
 * @className: RedisLock
 * @description: redis分布式锁
 * @create 2021/2/6 17:49
 **/
@Component
public class RedisLock {

    @Autowired
    public RedisTemplate redisTemplate;

    public static final int LOCK_EXPIRE = 3000; //单位毫秒

    /**
     * 添加分布式锁
     *
     * @param key
     * @return
     */
    public boolean lock(String key) {
        String lock = CacheKeyEnum.LOCK_KEY.getValue() + key;
        return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
            long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
            Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes());
            if (acquire) {
                return true;
            } else {
                byte[] value = connection.get(lock.getBytes());
                if (Objects.nonNull(value) && value.length > 0) {
                    long expireTime = Long.parseLong(new String(value));
                    if (expireTime < System.currentTimeMillis()) {
                        // 如果锁已经过期，设置新的过期时间
                        expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
                        byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(expireAt).getBytes());
                        // 防止死锁
                        return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
                    }
                }
            }
            return false;
        });
    }

    /**
     * 解锁
     *
     * @param key
     */
    public void unlock(String key) {
        String lock = CacheKeyEnum.LOCK_KEY.getValue() + key;
        redisTemplate.delete(lock);
    }
}
